package com.gh.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gh.client.DictFeignClient;
import com.gh.model.hosp.Department;
import com.gh.model.hosp.Hospital;
import com.gh.repository.DepartmentRepository;
import com.gh.repository.HospitalRepository;
import com.gh.service.HospitalService;
import com.gh.vo.hosp.DepartmentVo;
import com.gh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author Eric
 * @Date 2021/6/8 20:44
 * @Version 1.0
 */
@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    private HospitalRepository hospitalRepository;
    @Autowired
    private DictFeignClient dictFeignClient;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public void save(Map<String, Object> map) {
        //把参数map集合转换成对象hospital
        String mapString = JSONObject.toJSONString(map);
        Hospital hospital = JSONObject.parseObject(mapString, Hospital.class);
        //判断是否存在数据
        String hoscode = hospital.getHoscode();
        Hospital hospitalExist = hospitalRepository.getHospitalByHoscode(hoscode);
        //如果存在，进行修改
        if (hospitalExist != null) {
            hospital.setStatus(hospitalExist.getStatus());
            hospital.setCreateTime(hospitalExist.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        } else {
            //如果不存在进行添加
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }
    }

    @Override
    public Hospital getByHoscode(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        return hospital;
    }

    //医院列表，条件查询带分页
    @Override
    public Page<Hospital> selectHospPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        Pageable pageable = PageRequest.of(page - 1, limit);
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        hospital.setIsDeleted(0);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Example<Hospital> example = Example.of(hospital, exampleMatcher);
        Page<Hospital> pages = hospitalRepository.findAll(example, pageable);
        pages.getContent().forEach(item -> {
            String hostype = dictFeignClient.getName("Hostype", item.getHostype());//医院等级
            String province = dictFeignClient.getName(item.getProvinceCode());//省
            String city = dictFeignClient.getName(item.getCityCode());//市
            String district = dictFeignClient.getName(item.getDistrictCode());//地区
            item.getParam().put("hostype", hostype);
            item.getParam().put("fullAddress", province + city + district);
        });
        return pages;
    }

    @Override
    public void updateStatus(String id, Integer status) {
        Hospital hospital = hospitalRepository.findById(id).get();
        hospital.setStatus(status);
        hospital.setUpdateTime(new Date());
        hospitalRepository.save(hospital);
    }

    @Override
    public Map<String, Object> findHospitalById(String id) {
        Optional<Hospital> optional = hospitalRepository.findById(id);
        Hospital hospital = optional.get();
        String hostype = dictFeignClient.getName("Hostype", hospital.getHostype());//医院等级
        String province = dictFeignClient.getName(hospital.getProvinceCode());//省
        String city = dictFeignClient.getName(hospital.getCityCode());//市
        String district = dictFeignClient.getName(hospital.getDistrictCode());//地区
        hospital.getParam().put("hostype", hostype);
        hospital.getParam().put("fullAddress", province + city + district);

        Map<String, Object> map = new HashMap<>();
        map.put("bookingRule", hospital.getBookingRule());
        //不需要重新返回bookingRule
        hospital.setBookingRule(null);
        map.put("hospital", hospital);
        return map;
    }

    /**
     * 根据医院编号查询所有科室信息
     *
     * @param hoscode
     * @return
     */
    @Override
    public List<DepartmentVo> findDeptList(String hoscode) {
        List<DepartmentVo> list = new ArrayList<>();
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        Example<Department> example = Example.of(departmentQuery);
        List<Department> departmentList = departmentRepository.findAll(example);
        Map<String, List<Department>> map = departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));
        Set<Map.Entry<String, List<Department>>> entries = map.entrySet();
        for (Map.Entry<String, List<Department>> entry : entries) {
            DepartmentVo departmentVo = new DepartmentVo();
            departmentVo.setDepcode(entry.getKey());
            departmentVo.setDepname(entry.getValue().get(0).getBigname());
            List<DepartmentVo> listChildren = new ArrayList<>();
            entry.getValue().forEach(item -> {
                DepartmentVo departmentVoChildren = new DepartmentVo();
                departmentVoChildren.setDepcode(item.getDepcode());
                departmentVoChildren.setDepname(item.getDepname());
                listChildren.add(departmentVoChildren);
            });
            departmentVo.setChildren(listChildren);
            list.add(departmentVo);
        }
        return list;
    }

    @Override
    public List<Hospital> findByHosName(String hosname) {

        return hospitalRepository.findHospitalByHosnameLike(hosname);
    }

    @Override
    public Map<String, Object> findHospitalDetail(String hoscode) {
        Hospital hospital = this.getByHoscode(hoscode);//通过医院编号获取医院信息
        String hostype = dictFeignClient.getName("Hostype", hospital.getHostype());//医院等级
        String province = dictFeignClient.getName(hospital.getProvinceCode());//省
        String city = dictFeignClient.getName(hospital.getCityCode());//市
        String district = dictFeignClient.getName(hospital.getDistrictCode());//地区
        hospital.getParam().put("hostype", hostype);
        hospital.getParam().put("fullAddress", province + city + district);
        Map<String, Object> map = new HashMap<>();
        map.put("bookingRule", hospital.getBookingRule());
        //不需要重新返回bookingRule
        hospital.setBookingRule(null);
        map.put("hospital", hospital);
        return map;
    }
}
